package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.server.WebSocketServer;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@Component
public class OrderServiceImpl implements OrderService {
    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Value("${sky.baidu.output}")
    private String output;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    //服务API地址
    public static final String SERVICE_API_URL = "https://api.map.baidu.com/geocoding/v3";

    //规划路线地址
    public static final String DIRECTION_API_URL = "https://api.map.baidu.com/directionlite/v1/driving";

    /**
     * 检查客户的收获地址是否超出配送范围
     *
     * @param address
     * @return
     */
    public Boolean checkIsDistance(String address) {
        //1.将服务地址需要的参数封装成map集合
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("ak", ak);
        map.put("output", output);

        //2.获取店铺的经纬度坐标
        String shopAddress = HttpClientUtil.doGet(SERVICE_API_URL, map);
        //2.1将获得的字符串转为json对象
        JSONObject jsonObject = JSON.parseObject(shopAddress);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException(MessageConstant.SHOP_FAILED);
        }
        //3.解析店铺地址信息
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");

        //店铺经纬度坐标
        String shopLngAndLat = lat + "," + lng;
        log.info("店铺经纬度：{}",shopLngAndLat);

        //4.获取用户收获地址的经纬度坐标
        map.put("address", address);
        String userAddress = HttpClientUtil.doGet(SERVICE_API_URL, map);
        jsonObject = JSON.parseObject(userAddress);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException(MessageConstant.USER_FAILED);
        }
        //3.解析店铺地址信息
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");

        //配送地址经纬度坐标
        String userLngAndLat = lat + "," + lng;
        log.info("配送地址经纬度：{}",userLngAndLat);

        //4.将店铺地址和用户地址导入map,构造规划路线参数
        map.put("origin", shopLngAndLat);
        map.put("destination", userLngAndLat);
        map.put("steps_info", "0");

        //4.1规划路线接口
        String s = HttpClientUtil.doGet(DIRECTION_API_URL, map);
        jsonObject = JSON.parseObject(s);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException(MessageConstant.DIRECTION_FAILED);
        }

        //数据解析
        JSONArray result = (JSONArray) jsonObject.getJSONObject("result").get("routes");
        Integer distance = (Integer) ((JSONObject) result.get(0)).get("distance");
        log.info("两地间隔：{}",distance);

        return distance < 5000;
    }



    /*@Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;*/

    /**
     * 用户下单
     *
     * @param dto
     * @return
     */
    @Transactional   //0. 开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //获取当前登录人id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        //根据地址簿id查询地址信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //根据用户id查询购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.getByUserId(userId);
        if (cartList == null || cartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1. 构造订单数据对象orders，将orders插入到orders表中
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);

        if (!checkIsDistance(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail())) {
            throw new OrderBusinessException(MessageConstant.DISTANCE_FAILED);
        }

        //1.1 需要补充属性字段
        orders.setNumber(System.currentTimeMillis() + "");    //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);           //订单状态：1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setUserId(userId);                           //用户id
        orders.setOrderTime(LocalDateTime.now());           //下单时间
        orders.setPayStatus(Orders.UN_PAID);                //支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());            //联系人手机号
        orders.setAddress(addressBook.getDetail());         //收货地址
        orders.setConsignee(addressBook.getConsignee());    //收货人
        orders.setUserName(user.getName());                 //下单人

        orderMapper.insert(orders);
        log.info("订单id: {}", orders.getId());

        //2. 构造订单明细列表数据orderDetails，将orderDetails插入到order_detail表中
        //2.1 根据购物车的商品数据，构造订单明细
        List<OrderDetail> orderDetails = new ArrayList<>();
        cartList.forEach(cart -> {
            //2.2 将购物车对象的数据拷贝给订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            //2.3 关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);

        });
        orderDetailMapper.insertBatch(orderDetails);

        //3. 清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //4.构造vo对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        /*// 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));*/

        //业务处理，修改订单状态、来单提醒
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //支付成功之后，需要触发来单提醒
        Map paramMap = new HashMap();
        paramMap.put("type", 1);
        paramMap.put("orderId", ordersDB.getId());
        paramMap.put("content", ordersDB.getNumber());
        String message = JSON.toJSONString(paramMap);

        //调用websocket,主动推送消息给客户端
        webSocketServer.sendToAllClient(message);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        Long userId = BaseContext.getCurrentId();
        //1.获取地址簿
//        AddressBook addressBook = addressBookMapper.getByUserId(userId);

        //2.获取订单
        Orders order = orderMapper.getById(id);

        //3.获取订单详情
        List<OrderDetail> orderDetailLists = orderDetailMapper.getByOrderDetail(id);

        OrderVO orderVO = new OrderVO();

        BeanUtils.copyProperties(order, orderVO);

        orderVO.setOrderDetailList(orderDetailLists);

        return orderVO;
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.getAll(ordersPageQueryDTO);
        if (page != null && page.size() > 0) {
            page.getResult().forEach(orderVO -> {
                String string = "";
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderDetail(orderVO.getId());
                for (OrderDetail orderDetail : orderDetails) {
                    string += (orderDetail.getName() + "*" + orderDetail.getNumber() + ";");
                }
                orderVO.setOrderDishes(string.toString());
                string = "";
            });
        }
        return new PageResult(page.getTotal(), page.getResult());

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        Long userId = BaseContext.getCurrentId();
        //1.根据订单id查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderDetail(id);
        orderDetails.forEach(orderDetail -> {
            ShoppingCart cart = new ShoppingCart();
            cart.setName(orderDetail.getName());
            cart.setImage(orderDetail.getImage());
            cart.setUserId(userId);
            cart.setDishId(orderDetail.getDishId());
            cart.setDishId(orderDetail.getSetmealId());
            cart.setDishFlavor(orderDetail.getDishFlavor());
            cart.setNumber(orderDetail.getNumber());
            cart.setAmount(orderDetail.getAmount());
            cart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(cart);
        });
    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<OrderVO> orderVOList = orderMapper.getAll(ordersPageQueryDTO);
        for (OrderVO orderVO : orderVOList) {
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderDetail(orderVO.getId());
            orderVO.setOrderDetailList(orderDetails);
        }
        Page<OrderVO> page = (Page<OrderVO>) orderVOList;
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO){
        Orders order = orderMapper.getById(ordersCancelDTO.getId());
        Integer status = order.getStatus();
        BeanUtils.copyProperties(ordersCancelDTO, order);
        if (status == 1) {
            //模仿微信退款
        }

        order.setStatus(Orders.CANCELLED);
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);

    }

    @Override
    public void userCancel(Long id) {
        Orders order = orderMapper.getById(id);

        //校验id查询订单
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (order.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Integer status = order.getStatus();
        if (status.equals(Orders.TO_BE_CONFIRMED)) {
            //模仿微信退款

        }
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO getStatus() {
        Integer toBeConfirmed = orderMapper.getStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.getStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.getStatus(Orders.DELIVERY_IN_PROGRESS);
        return OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO detail(Long id) {
        Orders order = orderMapper.getById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderDetail(order.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        orderVO.setOrderDishes(JSON.toJSONString(orderDetails));
        return orderVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     * @return
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO, orders);
        //模仿微信退款
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     * @return
     */
    @Override
    public void delivery(Long id) {
        Orders order = orderMapper.getById(id);
        if (order == null || !order.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(order);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders order = orderMapper.getById(id);
        if (order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        order.setStatus(Orders.COMPLETED);
        order.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 催单
     *
     * @param id
     * @return
     */
    @Override
    public void reminder(Long id) {
        //1.构造响应数据
        Orders order = orderMapper.getById(id);
        Map paramMap = new HashMap();
        paramMap.put("type", 2); //2代表催单
        paramMap.put("orderId", id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        paramMap.put("content", order.getNumber());

        String jsonString = JSON.toJSONString(paramMap);

        //2.调用websocket,主动推送消息给前端
        webSocketServer.sendToAllClient(jsonString);
    }
}
